package com.wzs.easytobuy.controller;

import com.wzs.easytobuy.model.User;
import com.wzs.easytobuy.service.IUserService;
import com.wzs.easytobuy.utils.MD5Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author miaomiao
 * @version 1.0.0
 * @Description 处理与用户模块相关的请求
 * @createTime 2021-06-23- 09:14:00
 */
@Controller
public class UserController {

    @Resource
    private IUserService iUserService;

    @RequestMapping("/test.do")
    public String test() {
        return "test";
    }

    @RequestMapping("/Index.do")
    public String runHomePage() {
        return "Index";
    }

    @RequestMapping("/Login.do")
    public String Login() {
        return "Login";
    }

    @RequestMapping("/Register.do")
    public String Register() {
        return "Register";
    }

    @RequestMapping("/user/login.do")
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request, String username, String password) {

        String passwordMD5 = MD5Util.getMD5(password);

        try {
            User user = iUserService.login(username, passwordMD5);
            request.getSession().setAttribute("loginUser", user);
            Map<String, Object> map = new HashMap<>();
            map.put("success", true);

            return map;
        } catch (Exception e) {
            e.printStackTrace();

            String msg = e.getMessage();
            Map<String, Object> map = new HashMap<>();
            map.put("success", false);
            map.put("msg", msg);

            return map;

        }
    }

    @RequestMapping("/user/loginOut.do")
    public String loginOut(HttpSession session) {

        session.invalidate();

        return "Index";
    }


    @RequestMapping("/user/register.do")
    @ResponseBody
    public boolean register(User user) {

        boolean flag = true;

        int count = iUserService.register(user);
        if (count != 1) {
            flag = false;
        }

        int count1 = iUserService.addAddress(user);
        if (count1 != 1) {
            flag = false;
        }

        return flag;
    }

    @RequestMapping("/user/checkUserName.do")
    @ResponseBody
    public boolean checkUserName(String username) {

        boolean flag = true;

        int count = iUserService.checkUserName(username);

        if (count == 0) {
            flag = false;
        }

        return flag;
    }

    @RequestMapping("/user/checkEmail.do")
    @ResponseBody
    public boolean checkEmail(String email) {

        boolean flag = true;

        int count = iUserService.checkEmail(email);

        if (count == 0) {
            flag = false;
        }

        return flag;
    }


}
